<template>
  <view class="order-detail">
    <!-- 订单状态 -->
    <view class="status-section">
      <view class="status-info">
        <text class="status">{{ getStatusText(orderInfo.status) }}</text>
        <text class="desc">{{ getStatusDesc(orderInfo.status) }}</text>
      </view>
    </view>

    <!-- 收货地址 -->
    <view class="address-section">
      <view class="section-title">收货地址</view>
      <view class="address-info">
        <view class="user-info">
          <text class="name">{{ orderInfo.receiverName }}</text>
          <text class="phone">{{ orderInfo.receiverPhone }}</text>
        </view>
        <view class="address">{{ orderInfo.receiverAddress }}</view>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="goods-section">
      <view class="section-title">商品信息</view>
      <view class="merchant-info">
        <text class="merchant-name">{{ orderInfo.shopName }}</text>
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>
      <view class="goods-list">
        <view 
          v-for="item in orderInfo.orderItems" 
          :key="item.id"
          class="goods-item"
          @click="goToProduct(item.productId)"
        >
          <image class="goods-image" :src="item.productImage" mode="aspectFill"></image>
          <view class="goods-info">
            <view class="goods-name">{{ item.productName }}</view>
            <view class="goods-price">
              <text class="price">¥{{ item.price.toFixed(2) }}</text>
              <text class="quantity">x{{ item.quantity }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="section-title">订单信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="label">订单编号</text>
          <text class="value">{{ orderInfo.orderNo }}</text>
        </view>
        <view class="info-item">
          <text class="label">创建时间</text>
          <text class="value">{{ formatTime(orderInfo.createTime) }}</text>
        </view>
        <view class="info-item" v-if="orderInfo.payTime">
          <text class="label">支付时间</text>
          <text class="value">{{ formatTime(orderInfo.payTime) }}</text>
        </view>
        <view class="info-item" v-if="orderInfo.shipTime">
          <text class="label">发货时间</text>
          <text class="value">{{ formatTime(orderInfo.shipTime) }}</text>
        </view>
        <view class="info-item" v-if="orderInfo.receiveTime">
          <text class="label">收货时间</text>
          <text class="value">{{ formatTime(orderInfo.receiveTime) }}</text>
        </view>
        <view class="info-item">
          <text class="label">支付方式</text>
          <text class="value">{{ getPaymentMethod(orderInfo.payType) }}</text>
        </view>
        <view class="info-item" v-if="orderInfo.remark">
          <text class="label">订单备注</text>
          <text class="value">{{ orderInfo.remark }}</text>
        </view>
      </view>
    </view>

    <!-- 金额信息 -->
    <view class="amount-section">
      <view class="section-title">金额明细</view>
      <view class="amount-list">
        <view class="amount-item">
          <text class="label">商品总额</text>
          <text class="value">¥{{ orderInfo.totalAmount.toFixed(2) }}</text>
        </view>
        <view class="amount-item">
          <text class="label">运费</text>
          <text class="value">¥{{ orderInfo.freightAmount.toFixed(2) }}</text>
        </view>
        <view class="amount-item" v-if="orderInfo.couponAmount > 0">
          <text class="label">优惠券</text>
          <text class="value">-¥{{ orderInfo.couponAmount.toFixed(2) }}</text>
        </view>
        <view class="amount-item total">
          <text class="label">实付金额</text>
          <text class="value">¥{{ orderInfo.payAmount.toFixed(2) }}</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <template v-if="orderInfo.status === 0">
        <button class="action-btn cancel" @click="cancelOrder">取消订单</button>
        <button class="action-btn primary" @click="payOrder">立即支付</button>
      </template>
      <template v-else-if="orderInfo.status === 2">
        <button class="action-btn" @click="checkLogistics">查看物流</button>
        <button class="action-btn primary" @click="confirmOrder">确认收货</button>
      </template>
      <template v-else-if="orderInfo.status === 3">
        <button class="action-btn" @click="deleteOrder">删除订单</button>
        <button class="action-btn primary" @click="buyAgain">再次购买</button>
      </template>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderId: '',
      orderInfo: {
        id: '',
        orderNo: '',
        status: 0,
        shopName: '',
        createTime: '',
        payTime: '',
        shipTime: '',
        receiveTime: '',
        payType: 1,
        totalAmount: 0,
        freightAmount: 0,
        couponAmount: 0,
        payAmount: 0,
        receiverName: '',
        receiverPhone: '',
        receiverAddress: '',
        remark: '',
        orderItems: []
      }
    }
  },

  onLoad(options) {
    if (options.id) {
      this.orderId = options.id
      this.loadOrderDetail()
    }
  },

  methods: {
    // 加载订单详情
    async loadOrderDetail() {
      try {
        const res = await this.$api.orders.detail(this.orderId)
        if (res.data) {
          this.orderInfo = res.data
        }
      } catch (error) {
        console.error('加载订单详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },

    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    },

    // 获取订单状态描述
    getStatusDesc(status) {
      const descMap = {
        0: '请尽快完成支付',
        1: '商家正在处理订单',
        2: '商品正在配送中',
        3: '交易已完成',
        4: '订单已取消'
      }
      return descMap[status] || ''
    },

    // 获取支付方式文本
    getPaymentMethod(type) {
      const methodMap = {
        1: '支付宝支付',
        2: '微信支付',
        3: '余额支付'
      }
      return methodMap[type] || '未知方式'
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      return time.replace('T', ' ').split('.')[0]
    },

    // 跳转到商品详情
    goToProduct(productId) {
      uni.navigateTo({
        url: `/pages/product/detail/index?id=${productId}`
      })
    },

    // 取消订单
    async cancelOrder() {
      try {
        // 先询问是否确定取消
        const confirmRes = await uni.showModal({
          title: '提示',
          content: '确定要取消该订单吗？'
        })
        
        if (!confirmRes.confirm) return
        
        // 输入取消原因
        const reasonRes = await uni.showModal({
          title: '取消原因',
          content: '请选择取消原因',
          showCancel: true,
          confirmText: '其他原因',
          cancelText: '不想买了'
        })
        
        // 如果点击了其他原因，弹出输入框
        let reason = '不想买了'
        if (reasonRes.confirm) {
          const inputRes = await uni.showModal({
            title: '取消原因',
            editable: true,
            placeholderText: '请输入取消原因'
          })
          if (inputRes.confirm && inputRes.content) {
            reason = inputRes.content
          } else {
            return
          }
        }
        
        await this.$api.orders.cancel(this.orderId, reason)
        
        uni.showToast({
          title: '取消成功',
          icon: 'success'
        })
        this.loadOrderDetail()
      } catch (error) {
        uni.showToast({
          title: error.message || '取消失败',
          icon: 'none'
        })
      }
    },

    // 支付订单
    payOrder() {
      uni.navigateTo({
        url: `/pages/order/pay/index?orderId=${this.orderId}`
      })
    },

    // 查看物流
    checkLogistics() {
      uni.navigateTo({
        url: `/pages/order/logistics/index?orderId=${this.orderId}`
      })
    },

    // 确认收货
    async confirmOrder() {
      try {
        await this.$api.orders.confirm(this.orderId)
        uni.showToast({
          title: '确认成功',
          icon: 'success'
        })
        this.loadOrderDetail()
      } catch (error) {
        uni.showToast({
          title: error.message || '确认失败',
          icon: 'none'
        })
      }
    },

    // 删除订单
    async deleteOrder() {
      try {
        await this.$api.orders.delete(this.orderId)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        uni.showToast({
          title: error.message || '删除失败',
          icon: 'none'
        })
      }
    },

    // 再次购买
    buyAgain() {
      const productItems = this.orderInfo.orderItems.map(item => ({
        productId: item.productId,
        quantity: item.quantity
      }))
      uni.navigateTo({
        url: `/pages/order/submit/index?productItems=${JSON.stringify(productItems)}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-detail {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.status-section {
  background-color: #ff5500;
  padding: 40rpx 30rpx;
  color: #fff;

  .status-info {
    .status {
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
      display: block;
    }

    .desc {
      font-size: 26rpx;
      opacity: 0.9;
    }
  }
}

.section-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.address-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .address-info {
    .user-info {
      margin-bottom: 10rpx;

      .name {
        font-size: 30rpx;
        color: #333;
        margin-right: 20rpx;
      }

      .phone {
        font-size: 28rpx;
        color: #666;
      }
    }

    .address {
      font-size: 28rpx;
      color: #666;
      line-height: 1.4;
    }
  }
}

.goods-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .merchant-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #f5f5f5;

    .merchant-name {
      font-size: 28rpx;
      color: #333;
    }
  }

  .goods-list {
    .goods-item {
      display: flex;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f5f5f5;

      &:last-child {
        border-bottom: none;
      }

      .goods-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
      }

      .goods-info {
        flex: 1;
        margin-left: 20rpx;

        .goods-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
        }

        .goods-price {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .price {
            font-size: 32rpx;
            color: #ff5500;
          }

          .quantity {
            font-size: 26rpx;
            color: #999;
          }
        }
      }
    }
  }
}

.order-info-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .info-list {
    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        font-size: 28rpx;
        color: #666;
      }

      .value {
        font-size: 28rpx;
        color: #333;
      }
    }
  }
}

.amount-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .amount-list {
    .amount-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        font-size: 28rpx;
        color: #666;
      }

      .value {
        font-size: 28rpx;
        color: #333;
      }

      &.total {
        margin-top: 20rpx;
        padding-top: 20rpx;
        border-top: 1rpx solid #f5f5f5;

        .label {
          font-size: 30rpx;
          color: #333;
        }

        .value {
          font-size: 32rpx;
          color: #ff5500;
          font-weight: bold;
        }
      }
    }
  }
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: flex-end;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .action-btn {
    margin-left: 20rpx;
    padding: 0 30rpx;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 26rpx;
    border-radius: 30rpx;
    background-color: #fff;
    border: 1rpx solid #ddd;
    color: #666;

    &.primary {
      background-color: #ff5500;
      border-color: #ff5500;
      color: #fff;
    }

    &.cancel {
      border-color: #999;
      color: #999;
    }
  }
}
</style> 